package rpcserver

import (
	"encoding/json"
	"fmt"
	"reflect"
)

type Request struct {
	Pattern string
	Data    []byte
}

func (r *Request) String() string {
	return fmt.Sprintf("apiUrl: %s\nContent: %s", r.Pattern, string(r.Data))
}

type Response struct {
	Data []byte
}

type Context struct {
	Request  *Request
	Response *Response
}

func (c *Context) BindJSON(obj interface{}) (err error) {
	if err = json.Unmarshal(c.Request.Data, obj); err != nil {
		logger.Errorf("bind request data to %s failed", reflect.TypeOf(obj).Name())
	}
	return
}

func (c *Context) JSON(obj interface{}) error {
	bt, err := json.Marshal(obj)
	if err != nil {
		return err
	}
	c.Response.Data = bt
	return nil
}
